﻿Imports System.ComponentModel
Imports System.Text

Public Class PeerForm
    Private Sub PeerForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Peer1.Initialize()
    End Sub

    Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click
        txtLog.Text += vbNewLine & "Please wait..."
        Peer1.Login(txtDisplayName.Text, Guid.Parse("47E9B9E9-198E-4E83-8E4B-A394B429C36A"))
    End Sub

    Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
        Peer1.Send(Encoding.UTF8.GetBytes(txtMessage.Text))
        txtMessage.Text = String.Empty
    End Sub

    Private Sub Peer1_LinkDown(PeerID As String, PresenceInformation As Object) Handles Peer1.LinkDown
        Try
            Invoke(Sub()
                       txtLog.Text += vbNewLine & "Link down (" & PresenceInformation.ToString & ")"
                       btnSend.Enabled = False
                   End Sub)
        Catch
        End Try
    End Sub

    Private Sub Peer1_LinkUp(PeerID As String, PresenceInformation As Object) Handles Peer1.LinkUp
        Invoke(Sub()
                   txtLog.Text += vbNewLine & "Link up (" & PresenceInformation.ToString & ")"
                   btnSend.Enabled = True
               End Sub)
    End Sub

    Private Sub Peer1_LoginFailure() Handles Peer1.LoginFailure
        Invoke(Sub() txtLog.Text += vbNewLine & "Login failed...")
    End Sub

    Private Sub Peer1_LoginRetry(e As CancelEventArgs) Handles Peer1.LoginRetry
        If MsgBox("Retry login?", MsgBoxStyle.RetryCancel) = MsgBoxResult.Retry Then
            e.Cancel = False
        Else
            e.Cancel = True
        End If
    End Sub

    Private Sub Peer1_LoginSuccess() Handles Peer1.LoginSuccess
        Invoke(Sub() txtLog.Text += vbNewLine & "Logged in!")
    End Sub

    Private Sub Peer1_Receive(FromPeerID As String, PresenceInformation As Object, Payload() As Byte) Handles Peer1.Receive
        Invoke(Sub() txtLog.Text += vbNewLine & PresenceInformation.ToString & ": " & Encoding.UTF8.GetString(Payload))
    End Sub

End Class